<template>
  <el-dialog
    :title="title"
    :visible.sync="visible"
    width="1400px"
    :close-on-click-modal="false"
    :modal-append-to-body="false"
    :append-to-body="true"
    :before-close="handleClose"
  >
    <el-row :gutter="24">
      <el-col :span="13">
        <el-card header="基础配置">
          <el-form
            ref="columnEdit"
            :model="column"
            :rules="rules"
            label-width="150px"
          >
            <el-form-item label="所属组别" prop="GroupId">
              <el-cascader
                v-model="column.GroupId"
                placeholder="所属组别"
                :clearable="true"
                :props="{
                  emitPath: false,
                  label: 'Name',
                  value: 'Id',
                  children: 'Children'
                }"
                :options="groups"
              />
            </el-form-item>
            <el-form-item label="标题" prop="ColLabel">
              <el-input
                v-model="column.ColLabel"
                :maxlength="50"
                placeholder="标题"
              />
            </el-form-item>
            <el-form-item label="列名" prop="ColName">
              <el-input
                v-model="column.ColName"
                :maxlength="50"
                placeholder="列名"
              />
            </el-form-item>
            <el-form-item label="呈现方式" prop="ShowMode">
              <enumItem
                v-model="column.ShowMode"
                :dic-key="EnumDic.PhyColShowMode"
                placeholder="呈现方式"
                sys-head="form"
                @change="showModeChange"
              />
            </el-form-item>
            <el-form-item v-if="column.ShowMode != 0" label="来源列" prop="SourceCol">
              <el-cascader
                v-model="column.SourceCol"
                placeholder="来源列"
                :clearable="true"
                :props="{
                  emitPath: false,
                  label: 'Label',
                  value: 'Id',
                  children: 'Children'
                }"
                :options="filterColumn()"
              />
            </el-form-item>
            <template v-else>
              <el-form-item label="存储类型" prop="DataType">
                <enumItem
                  v-model="column.DataType"
                  :dic-key="EnumDic.PhyTableDataType"
                  placeholder="存储类型"
                  sys-head="form"
                />
              </el-form-item>
              <el-form-item v-if="column.DataType == 0 || column.DataType == 1 || column.DataType == 4" label="长度" prop="ColLen">
                <el-input-number
                  v-model="column.ColLen"
                  :min="1"
                  placeholder="长度"
                />
              </el-form-item>
              <el-form-item v-else-if="column.DataType == 2" label="小数位" prop="Precision">
                <el-input-number
                  v-model="column.Precision"
                  :min="0"
                  :max="10"
                  placeholder="小数位"
                />
              </el-form-item>
              <el-form-item label="数据类型" prop="FuncType">
                <enumItem
                  v-model="column.FuncType"
                  :dic-key="EnumDic.FormColumnFuncType"
                  placeholder="数据类型"
                  sys-head="form"
                  @change="showModeChange"
                />
              </el-form-item>
              <el-form-item v-if="column.ShowMode == 0 && column.FuncType == 4" label="字典项" prop="DictId">
                <el-cascader
                  v-model="column.DictId"
                  :options="dict"
                  placeholder="请选择字典项"
                  :props="colPoprs"
                  :clearable="true"
                  style="min-width: 200px"
                  class="el-input"
                />
              </el-form-item>
              <el-form-item label="默认值" prop="DefValue">
                <el-input
                  v-model="column.DefValue"
                  :maxlength="50"
                  placeholder="默认值"
                />
              </el-form-item>
              <el-form-item label="是否可空" prop="IsNull">
                <el-switch
                  v-model="column.IsNull"
                  active-text="可为空"
                  inactive-text="不能为空"
                />
              </el-form-item>
              <el-form-item label="是否隐藏" prop="IsHidden">
                <el-switch
                  v-model="column.IsHidden"
                  active-text="隐藏"
                  inactive-text="显示"
                />
              </el-form-item>
              <el-form-item label="列表中隐藏" prop="IsQueryHide">
                <el-switch
                  v-model="column.IsQueryHide"
                  active-text="隐藏"
                  inactive-text="显示"
                />
              </el-form-item>
            </template>
            <el-form-item label="列最小宽" prop="Width">
              <el-input-number
                v-model="column.Width"
                :precision="0"
                placeholder="列最小宽"
              />
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>
      <el-col :span="10" :offset="1">
        <el-card header="扩展配置">
          <el-form
            ref="columnSet"
            :model="columnSet"
            label-width="120px"
          >
            <el-form-item label="整行显示" prop="IsRow">
              <el-switch
                v-model="columnSet.IsRow"
              />
            </el-form-item>
            <el-form-item v-if="column.ShowMode == 0 && column.FuncType == 5" label="目录名称" prop="DirKey">
              <fileDirSelect v-model="columnSet.DirKey" placeholder="文件目录名" />
            </el-form-item>
            <el-form-item v-if="column.ShowMode == 7" label="选项值">
              <el-row v-for="(t,i) in columnSet.Items" :key="i" style="margin-top: 5px;">
                <el-col :span="8">
                  <el-input v-model="t.text" placeholder="文本" />
                </el-col>
                <el-col :span="2" style="text-align: center;">:</el-col>
                <el-col :span="8">
                  <el-input v-model="t.value" placeholder="值" />
                </el-col>
                <el-col :span="6" style="text-align: center;">
                  <el-button v-if="i != 0 && columnSet.Items.length != 1" type="text" icon="el-icon-top" @click="upItem(i)" />
                  <el-button v-if="(i+1) != columnSet.Items.length && columnSet.Items.length != 1" type="text" icon="el-icon-bottom" @click="downItem(i)" />
                  <el-button type="text" icon="el-icon-delete" @click="dropItem(i)" />
                </el-col>
              </el-row>
              <el-button icon="el-icon-plus" type="success" style="width: 100%; margin-top: 5px;" @click="addItem(item)" />
            </el-form-item>
            <template v-if="column.DataType ==5">
              <el-form-item label="打开时的文字" prop="ActiveText">
                <el-input
                  v-model="columnSet.ActiveText"
                  :maxlength="10"
                  placeholder="打开时的文字"
                />
              </el-form-item>
              <el-form-item label="关闭时的文字" prop="InactiveText">
                <el-input
                  v-model="columnSet.InactiveText"
                  :maxlength="10"
                  placeholder="关闭时的文字"
                />
              </el-form-item>
            </template>
            <el-form-item v-if="column.DataType != 3 && column.DataType < 6 && column.DataType > 9" label="数据格式" prop="Format">
              <el-select v-model="columnSet.Format" placeholder="选择数据格式" clearable>
                <el-option label="无" value="" />
                <el-option-group v-if="column.DataType == 3 || column.DataType == 6 || column.DataType == 9" label="数字格式">
                  <el-option label="小时分" value="time" />
                  <el-option label="百分比" value="ratio" />
                </el-option-group>
                <el-option-group v-else-if="column.DataType == 8" label="日期格式">
                  <el-option label="2025/01/01" value="YYYY/MM/DD" />
                  <el-option label="2025-01-01" value="YYYY-MM-DD" />
                  <el-option label="2025年01月01日" value="YYYY年MM月DD日" />
                </el-option-group>
                <el-option-group v-else-if="column.DataType == 7" label="时间格式">
                  <el-option label="2025/01/01 12:05" value="YYYY/MM/DD HH:mm" />
                  <el-option label="2025-01-01 12:05" value="YYYY-MM-DD HH:mm" />
                  <el-option label="2025年01月01日 HH:mm" value="YYYY年MM月DD日 HH:mm" />
                </el-option-group>
              </el-select>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>
    </el-row>
    <div slot="footer" style="text-align: center">
      <el-button type="primary" @click="save">保存</el-button>
      <el-button @click="reset">重置</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { GetItems } from '@/api/base/dict'
import * as columnApi from '@/customForm/api/phyQueryColumn'
import { EnumDic } from '@/customForm/config/formConfig'
import fileDirSelect from '@/components/file/fileDirSelect.vue'
export default {
  components: {
    fileDirSelect
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    tableId: {
      type: String,
      default: null
    },
    id: {
      type: String,
      default: null
    },
    formId: {
      type: String,
      default: null
    },
    columns: {
      type: Array,
      default: () => []
    },
    groupId: {
      type: String,
      default: null
    }
  },
  data() {
    return {
      EnumDic,
      title: '编辑物理列',
      colPoprs: {
        multiple: false,
        emitPath: false,
        checkStrictly: false,
        value: 'Id',
        label: 'DicName',
        children: 'Children'
      },
      column: {},
      groups: [],
      dict: [],
      ver: 1,
      columnSet: {},
      rules: {
        ColLabel: [
          {
            required: true,
            message: '标题不能为空！',
            trigger: 'blur'
          }
        ],
        ColName: [
          {
            required: true,
            message: '列名不能为空！',
            trigger: 'blur'
          },
          {
            pattern: /^[a-zA-Z_]+$/g,
            message: '列名只能由英文和_组成！',
            trigger: 'blur'
          }
        ],
        ControlId: [
          {
            required: true,
            message: '请选择控件！',
            trigger: 'blur'
          }
        ]
      },
      control: {}
    }
  },
  watch: {
    visible: {
      handler(val) {
        if (val) {
          this.reset()
        }
      },
      immediate: true
    }
  },
  mounted() {},
  methods: {
    filterColumn() {
      let funcType = 0
      if (this.column.ShowMode === 1) {
        funcType = 1
      } else if (this.column.ShowMode === 2 || this.column.ShowMode === 3 || this.column.ShowMode === 4) {
        funcType = 2
      } else {
        funcType = 4
      }
      const rows = []
      this.filter(funcType, this.columns, rows)
      return rows
    },
    filter(funcType, columns, list) {
      columns.forEach(c => {
        const data = Object.assign({}, c)
        if (c.IsGroup) {
          const rows = []
          this.filter(funcType, c.Children, rows)
          if (rows.length > 0) {
            data.Children = rows
            list.push(data)
          }
        } else if (c.FuncType === funcType) {
          list.push(data)
        }
      })
    },
    async showModeChange() {
      if (this.column.ShowMode === 0 && this.column.FuncType === 4) {
        const res = await GetItems(null)
        this.dict = [{
          Id: 0,
          DicName: '普通字典',
          Children: res.filter(c => c.IsTreeDic === false)
        }, {
          Id: 0,
          DicName: '树形字典',
          Children: res.filter(c => c.IsTreeDic === true)
        }]
      }
    },
    upItem(index) {
      const arr = this.columnSet.Items
      const t = arr[index]
      arr[index] = arr[index - 1]
      arr[index - 1] = t
      this.columnSet.Items = arr.concat()
    },
    downItem(index) {
      const arr = this.columnSet.Items
      const t = arr[index]
      arr[index] = arr[index + 1]
      arr[index + 1] = t
      this.columnSet.Items = arr.concat()
    },
    dropItem(index) {
      this.columnSet.Items.splice(index, 1)
      this.ver = this.ver + 1
    },
    addItem() {
      this.columnSet.Items.push({
        text: null,
        value: null
      })
      this.ver = this.ver + 1
    },
    initColumns(groups, data) {
      if (groups == null || groups.length === 0) {
        return
      }
      groups.forEach(a => {
        if (a.IsGroup) {
          const g = {
            Id: a.Id,
            Name: a.Label,
            Children: null
          }
          this.initColumns(a.Children, g)
          data.Children.push(g)
        }
      })
    },
    initGroup() {
      const list = []
      this.columns.forEach(a => {
        if (a.IsGroup) {
          const g = {
            Id: a.Id,
            Name: a.Label,
            Children: null
          }
          this.initColumns(a.Children, g)
          list.push(g)
        }
      })
      this.groups = list
    },
    async reset() {
      this.initGroup()
      if (this.id != null) {
        const res = await columnApi.Get(this.id)
        this.title = '编辑控件(' + res.ColLabel + ')配置'
        this.column = {
          GroupId: res.GroupId,
          ColLabel: res.ColLabel,
          ColName: res.ColName,
          DataType: res.DataType,
          IsNull: res.IsNull,
          DefValue: res.DefValue,
          FuncType: res.FuncType,
          IsQueryHide: res.IsQueryHide,
          ColLen: res.ColLen,
          ShowMode: res.ShowMode,
          DictId: res.DictId,
          SourceCol: res.SourceCol,
          Precision: res.Precision,
          IsHidden: res.IsHidden,
          Width: res.Width
        }
        if (res.ColumnSet == null) {
          this.columnSet = {
            Format: null,
            DirKey: null,
            ActiveText: '是',
            InactiveText: '否',
            IsRow: false,
            Items: []
          }
        } else {
          this.columnSet = {
            Format: res.ColumnSet.Format,
            DirKey: res.ColumnSet.DirKey,
            ActiveText: res.ColumnSet.ActiveText ? res.ColumnSet.ActiveText : '是',
            InactiveText: res.ColumnSet.InactiveText ? res.ColumnSet.InactiveText : '否',
            IsRow: res.ColumnSet.IsRow,
            Items: res.ColumnSet.Items == null ? [] : res.ColumnSet.Items
          }
        }
        this.showModeChange()
      } else {
        this.title = '新增控件'
        this.column = {
          GroupId: this.groupId,
          ColLabel: null,
          ColName: null,
          DefValue: null,
          FuncType: 0,
          DataType: null,
          IsNull: false,
          SourceCol: null,
          IsQueryHide: false,
          ShowMode: 0,
          ColLen: 50,
          Precision: 2,
          IsHidden: false,
          Width: 120
        }
        this.columnSet = {
          Format: null,
          DirKey: null,
          ActiveText: '是',
          InactiveText: '否',
          IsRow: false,
          Items: []
        }
      }
    },
    handleClose() {
      this.$emit('update:visible', false)
      this.$emit('close', false)
    },
    async set() {
      const data = this.format()
      const isSet = await columnApi.Set(this.id, data)
      this.$emit('update:visible', false)
      this.$emit('close', isSet, this.id)
    },
    format() {
      const data = Object.assign({}, this.column)
      data.ColumnSet = {
        IsRow: this.columnSet.IsRow
      }
      if (this.column.ShowMode !== 0) {
        data.DataType = 1
        data.ColLen = 50
      }
      if (this.column.ShowMode === 7) {
        data.ColumnSet.Items = this.columnSet.Items
      }
      if (this.column.ShowMode === 0 && this.column.FuncType === 5) {
        data.ColumnSet.DirKey = this.columnSet.DirKey
      }
      if (data.DataType === 5) {
        data.ColumnSet.ActiveText = this.columnSet.ActiveText
        data.ColumnSet.InactiveText = this.columnSet.InactiveText
      } else if (data.DataType === 3 || data.DataType === 6 || data.DataType === 9) {
        data.ColumnSet.Format = this.columnSet.Format
      }
      return data
    },
    async add() {
      const data = this.format()
      data.FormId = this.formId
      data.TableId = this.tableId
      const id = await columnApi.Add(data)
      this.$emit('update:visible', false)
      this.$emit('close', true, id)
    },
    save() {
      this.$refs['columnEdit'].validate((valid) => {
        if (valid) {
          if (this.id == null) {
            this.add()
          } else {
            this.set()
          }
        } else {
          return false
        }
      })
    }
  }
}
</script>
<style scoped>
.rule {
  width: 100%;
  line-height: 20px;
}
.rule .warn {
  display: inline-block;
  width: 10px;
  height: 10px;
  background-color:rgb(235, 181, 99);
  margin-right: 5px;
  border-radius: 20px;
}
.rule .error {
  display: inline-block;
  width: 10px;
  height: 10px;
  background-color: #e4393c;
  margin-right: 5px;
  border-radius: 20px;
}
</style>
